package com.goldgov.branchCircle.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.branchCircle.service.Attention;
import com.goldgov.branchCircle.service.AttentionQuery;
import com.goldgov.branchCircle.service.AttentionService;
import com.goldgov.branchCircle.service.BranchCircle;
import com.goldgov.branchCircle.service.BranchCircleQuery;
import com.goldgov.branchCircle.service.BranchCircleService;
import com.goldgov.branchCircle.service.Message;
import com.goldgov.branchCircle.service.MessageService;
import com.goldgov.branchCircle.service.ReplyMessage;
import com.goldgov.branchCircle.service.ReplyMessageService;
import com.goldgov.branchCircle.service.ThumbUp;
import com.goldgov.branchCircle.service.ThumbUpService;
import com.goldgov.kcloud.core.json.JsonErrorObject;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.learnmanage.service.User;
import com.goldgov.learnmanage.service.UserService;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.securityworkbench.attachment.AttachementBean;
import com.goldgov.sensitive.service.Sensitive;
import com.goldgov.sensitive.service.SensitiveService;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.PrintUtil;
import com.goldgov.utils.PropertyUtil;
import com.goldgov.utils.UrlUtil;

import feign.Body;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/** 
 * @ClassName: BranchCircleController 
 * @Description: TODO
 * @author MaN
 * @date 2018年6月19日 
 */

@RestController
@RequestMapping("/portal/branchCircle")
@Api("支部圈接口")
public class BranchCircleForPortalController {

	@Autowired
	private BranchCircleService branchCircleService;
	
	@Autowired
	private ThumbUpService thumbUpService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private ReplyMessageService replyMessageService;
	
	@Autowired
	private SensitiveService service;
	
	@Autowired
	private AttentionService attentionService;
	
	@Autowired
	private RemoteCallService remoteCallService;
	@Autowired
	private UserService userService;
	/**
	 * 预新增
	 * @param obj
	 * @param request
	 * @return
	 */
	
	@GetMapping("/preAddBranchCircle")
	@ApiOperation(value = "预新增支部圈", notes ="查询返回支部圈ID")
	public JsonSuccessObject<BranchCircle> preAddBranchCircle(BranchCircle obj,HttpServletRequest request){
		obj = branchCircleService.getBranchID();
		JsonSuccessObject<BranchCircle> returnResult = new JsonSuccessObject<BranchCircle>(obj);
		return returnResult;
	}
	
	@PostMapping
	@ApiOperation(value = "新增支部圈", notes ="")
	public void addBranchCircle(BranchCircle obj,HttpServletResponse response,HttpServletRequest request){
		String flag=service.judgeSensitive(obj.getBranchContent());
		LoginAuthUser u=LoginAuthUser.getUser(request);
		//flag不为空时代表含有关键词，返回状态为2000，否则为5000
		if(!flag.equals("")) {
			Sensitive s=new Sensitive();
			s.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			s.setDataID(obj.getBranchID());
			s.setDataSource("支部圈");
			s.setDataTitle(obj.getBranchContent());
			s.setTriggerValue(flag);
			s.setDataTable("gt_conference");
			s.setTriggerUserID(u.getEntityID());
			s.setTriggerUserName(u.getUserName());
			service.addSensitive(s);
		}
		obj.setUserID(u.getEntityID());//发布人id
		obj.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
		obj.setPublishDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		try {
			branchCircleService.addBranchCircle(obj);
			PrintUtil.print(response, true);
		} catch (Exception e) {
			PrintUtil.print(response, false);
			e.printStackTrace();
		}
	}
	
	@GetMapping
	@ApiOperation(value = "支部圈列表", notes ="")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBranchID", value = "支部圈id", paramType = "query"),
		 @ApiImplicitParam(name = "searchOrgID", value = "机构id", paramType = "query"),
		 @ApiImplicitParam(name = "searchType", value = "查询方式", paramType = "query")})
	public JsonQueryObject<BranchCircle> listBranchCircle(@ApiIgnore BranchCircleQuery query,HttpServletRequest request){
		Integer type=query.getSearchType();
		if(null!=type && type==2) {//近一天
			Date d=new Date(); 
		    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
		    String endTime=df.format(d);
			String beginTime=df.format(new Date(d.getTime() - 24 * 60 * 60 * 1000));
			query.setSearchBeginTime(beginTime);
			query.setSearchEndTime(endTime);
		}else if(null!=type && type==3){//近一周
			Date d=new Date(); 
		    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
		    String endTime=df.format(d);
		    String beginTime=df.format(new Date(d.getTime() - 6 * 24 * 60 * 60 * 1000));
			query.setSearchBeginTime(beginTime);
			query.setSearchEndTime(endTime);
		}else if(null!=type && type==4){//近一月
			Date d=new Date(); 
		    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
		    String endTime=df.format(d);
		    String beginTime=df.format(new Date(d.getTime() - 30 * 24 * 60 * 60 * 1000));
			query.setSearchBeginTime(beginTime);
			query.setSearchEndTime(endTime);
		}
		List<BranchCircle> list=branchCircleService.getBranchCircleList(query);
		if(null!=list && list.size()>0) {
			for(BranchCircle b:list) {
				
				if(null!=b.getHeadPhotoUrl() && !"".equals(b.getHeadPhotoUrl())) {
					b.setHeadPhotoUrl(UrlUtil.ATTACHEMEMENT_URL + b.getHeadPhotoUrl());  
				}else {
					b.setHeadPhotoUrl("/static/image/manner-image/default-headPhoto.png");
				}
				
				 Map params=new HashMap();
					params.put("groupId", b.getBranchID());
					String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
					JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
					JSONArray jsonList=json.getJSONArray("resultList");
					List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
					for(AttachementBean att:ab) {
						att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
						if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
							att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
						}else {
							att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
						}
					}
					b.setFileList(ab);
			}
		}
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	@GetMapping("/deleteBranchCircle")
	@ApiOperation(value = "删除支部圈", notes ="")
	public JsonObject<Object> deleteBranchCircle(@ApiParam(value = "branchID", required = true) @RequestParam("branchID") String branchID,HttpServletRequest request){
		branchCircleService.deleteBranchCircle(branchID);
		return JsonSuccessObject.SUCCESS;
	}
	
	@GetMapping("/updateThumbUp")
	@ApiOperation(value = "点赞/取消点赞", notes ="")
	public JsonObject<Object> saveThumbUp(@ApiParam(value = "branchID", required = true) @RequestParam("branchID") String branchID,HttpServletResponse response,HttpServletRequest request){
		ThumbUp up=new ThumbUp();
		LoginAuthUser u=LoginAuthUser.getUser(request);
		up.setUserID(u.getEntityID());
		up.setUserName(u.getUserName());
		up.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		up.setBranchID(branchID);
		try {
			thumbUpService.saveThumbUp(up);
			return JsonSuccessObject.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return JsonErrorObject.ERROR;
		}
	}
	
	@PostMapping("/addMessage")
	@ApiOperation(value = "新增留言", notes ="")
	public void addMessage(Message obj,HttpServletResponse response,HttpServletRequest request) throws IOException{
		LoginAuthUser u=LoginAuthUser.getUser(request);
		obj.setUserID(u.getEntityID());//留言人id
		obj.setUserName(u.getUserName());//留言人姓名
		obj.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
		obj.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		response.setContentType("application/json");
		PrintWriter pw=response.getWriter();
		JSONObject o=new JSONObject();
		try {
			messageService.addMessage(obj);
			o.put("messageID",obj.getMessageID());
			o.put("code", "2000");
		} catch (Exception e) {
			o.put("code", "5000");
			e.printStackTrace();
		}
		pw.write(o.toJSONString());
		pw.flush();
		pw.close();
	}
	
	@PostMapping("/replyMessage")
	@ApiOperation(value = "回复留言", notes ="")
	@Body(value = "")
	public void addReplyMessage(ReplyMessage obj,HttpServletResponse response,HttpServletRequest request) throws IOException{
		LoginAuthUser u=LoginAuthUser.getUser(request);
		obj.setReplyUserID(u.getEntityID());//回复留言人id
		obj.setReplyUserName(u.getUserName());//回复留言人姓名
		obj.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
		obj.setReplyDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		response.setContentType("application/json");
		PrintWriter pw=response.getWriter();
		JSONObject o=new JSONObject();
		try {
			replyMessageService.addReplyMessage(obj);
			o.put("replyID",obj.getReplyMessageID());
			o.put("code", "2000");
		} catch (Exception e) {
			o.put("code", "5000");
			e.printStackTrace();
		}
		pw.write(o.toJSONString());
		pw.flush();
		pw.close();
	}
	
	@GetMapping("/updateAttention")
	@ApiOperation(value = "添加/取消关注", notes ="")
	public JsonObject<Object> saveAttention(@ApiParam(value = "orgID", required = true) @RequestParam("orgID") String orgID,HttpServletResponse response,HttpServletRequest request){
		LoginAuthUser u=LoginAuthUser.getUser(request);
		try {
			attentionService.saveAttention(orgID, u.getEntityID());
			return JsonSuccessObject.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return JsonErrorObject.ERROR;
		}
	}
	@GetMapping("/listAttention")
	@ApiOperation(value = "关注列表", notes ="")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchUserID", value = "用户id", paramType = "query")})
	public JsonQueryObject<Attention> getAttentionList(@ApiIgnore AttentionQuery query,HttpServletResponse response,HttpServletRequest request){
		LoginAuthUser u=LoginAuthUser.getUser(request);
		query.setSearchUserID(u.getEntityID());
		List<Attention> list=attentionService.getAttentionList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	@GetMapping("/listXgOrg")
	@ApiOperation(value = "相关支部", notes ="")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchOrgID", value = "部门id", paramType = "query")})
	public JsonQueryObject<Attention> getXgOrgList(@ApiIgnore AttentionQuery query,HttpServletResponse response,HttpServletRequest request){
		String treePath=attentionService.getTreePathByID(query.getSearchOrgID());
		int length=treePath.length();
		String [] path=treePath.split("/");
		if(null!=path && path.length>1) {
			query.setSearchParentID(path[path.length-2]);
			int index=treePath.substring(0,length-2).lastIndexOf("/");
			query.setSearchTreePath(treePath.substring(0, index+1));
		}
		List<Attention> list=attentionService.getXgOrgList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	@GetMapping("/listTjOrg")
	@ApiOperation(value = "推荐支部", notes ="")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchOrgID", value = "部门id", paramType = "query")})
	public JsonQueryObject<Attention> getTjOrgList(@ApiIgnore AttentionQuery query,HttpServletResponse response,HttpServletRequest request){
		String treePath=attentionService.getTreePathByID(query.getSearchOrgID());
		int length=treePath.length();
		String [] path=treePath.split("/");
		if(null!=path && path.length>1) {
			query.setSearchParentID(path[path.length-2]);
			int index=treePath.substring(0,length-2).lastIndexOf("/");
			query.setSearchTreePath(treePath.substring(0, index+1));
		}
		List<Attention> list=attentionService.getTjOrgList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	@GetMapping("/listOrgByName")
	@ApiOperation(value = "搜索支部", notes ="")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchOrgName", value = "支部名称", paramType = "query")})
	public JsonQueryObject<Attention> getOrgListByName(@ApiIgnore AttentionQuery query,HttpServletResponse response,HttpServletRequest request){
		List<Attention> list=attentionService.getOrgList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	
	@GetMapping("/findAboutOrg")
	@ApiOperation(value = "查询支部人员及关注情况", notes ="")
	public JsonSuccessObject<Attention> findAboutOrg(@ApiParam(value = "orgID", required = true) @RequestParam("orgID") String orgID,HttpServletResponse response,HttpServletRequest request,Model model){
		LoginAuthUser u=LoginAuthUser.getUser(request);
		//LoginAuthUser u=LoginAuthUser.getUserTest(request);
			Attention attention=attentionService.findAttentionOrg(orgID, u.getEntityID());
			List<User> list=userService.findOrgUser(orgID);
			if(attention!=null) {
				attention.setUserID(u.getEntityID());
				attention.setUserList(list);
			}
			return new JsonSuccessObject<Attention>(attention);
	} 
}
